package app

import (
	"context"
	"core/repo"
	"framework/node"
	"go.uber.org/zap"
	"hall/route"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func Run(ctx context.Context, serverId string) error {
	exit := func() {}
	go func() {
		c := node.Default("hall") //初始化一个node实例
		repoManager := repo.New()
		c.RegisterHandler(route.Register(repoManager))
		c.Run(serverId)
	}()
	stop := func() {
		exit()
		time.Sleep(3 * time.Second)
		zap.S().Info("app hall do stop finally by signal")
	}
	//期望有一个优雅的启停，遇到中断 退出 终止 挂断
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGHUP)
	for {
		select {
		case <-ctx.Done():
			stop()
			//time out
			return nil
		case s := <-c:
			switch s {
			case syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT:
				stop()
				zap.S().Info("app hall quit")
				return nil
			case syscall.SIGHUP:
				stop()
				zap.S().Info("hang up! app hall quit")
				return nil
			default:
				return nil
			}
		}
	}
}
